package com.tencreat.service.im.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tencreat.common.config.OpenIMConfig;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.domain.model.LoginUser;
import com.tencreat.common.core.domain.model.LoginUserIM;
import com.tencreat.common.core.service.TokenService;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.bean.BeanUtils;
import com.tencreat.domain.account.MallUser;
import com.tencreat.domain.im.ImCustomer;
import com.tencreat.domain.im.dto.*;
import com.tencreat.domain.im.vo.OpenIMAccountCheckVo;
import com.tencreat.domain.im.vo.OpenIMAccountCheckWrapVo;
import com.tencreat.domain.im.vo.OpenIMResultVo;
import com.tencreat.domain.im.vo.OpenIMTokenVo;
import com.tencreat.mapper.im.ImCustomerMapper;
import com.tencreat.service.account.IMallUserService;
import com.tencreat.service.im.IImCustomerService;
import com.tencreat.service.im.OpenIMApi;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * IM  客服Service业务层处理
 *
 * @author tencreat
 * @company 深圳腾创互联科技有限公司
 * @link https://tencreat.com
 * @since 2023-11-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
@Slf4j
public class ImCustomerServiceImpl extends ServiceImpl<ImCustomerMapper, ImCustomer> implements IImCustomerService {

    private final OpenIMApi openIMApi;
    private final IMallUserService mallUserService;
    private final TokenService tokenService;

    /**
     * 分页查询
     *
     * @param iPage      分页参数
     * @param imCustomer 查询条件
     * @return 分页结果
     */
    @Override
    public IPage<ImCustomer> page(IPage<?> iPage, ImCustomer imCustomer) {
        return baseMapper.page(iPage, imCustomer);
    }

    @Override
    public OpenIMResultVo<OpenIMTokenVo> loginIM(OpenIMLoginDTO openIMLoginDTO, Long uuid) {
        OpenIMConfig openIMConfig = OpenIMConfig.getOpenIMConfig();
        // 导入IM账号
        MallUser one = mallUserService.lambdaQuery().eq(MallUser::getUuid, uuid).one();
        // 查看用户是否存在， 存在则不创建
        OpenIMResultVo<OpenIMAccountCheckWrapVo> listOpenIMResultVo = openIMApi.accountCheck(new OpenIMAccountCheckDTO(one.getUuid().toString()));
        if (listOpenIMResultVo.getData() == null || !listOpenIMResultVo.getData().getResults().get(0).getAccountStatus().equals(OpenIMAccountCheckVo.REGISTERED)) {
            OpenIMRegisterDTO openIMRegisterDTO = new OpenIMRegisterDTO(openIMConfig.getSecret(), one.getUuid().toString(), one.getNickname(), openIMConfig.getAvatarUser());
            // 添加openIM账户
            OpenIMResultVo<String> result = openIMApi.userRegister(openIMRegisterDTO);
            if (result.getErrCode() == 0) {
                // 如果是普通用户登录， 需要把客服加入群聊
                if (openIMLoginDTO.getPlatformID() != 10) {
                    // 每个人都有一个群
                    OpenIMCreateGroupDTO openIMCreateGroupDTO = new OpenIMCreateGroupDTO(one);
                    // 查找所有客服， 然后加进来
                    List<ImCustomer> list = list();
                    List<String> imIds = list.stream().map(ImCustomer::getImId).collect(Collectors.toList());
                    openIMCreateGroupDTO.setMemberUserIDs(imIds);
                    openIMCreateGroupDTO.getGroupInfo().setFaceURL(openIMConfig.getAvatarUser());
//                    openIMCreateGroupDTO.setAdminUserIDs(imIds);
                    // 创建一个群聊
                    OpenIMResultVo<OpenIMGroupInfo> groupInfo = openIMApi.createGroup(openIMCreateGroupDTO);
                    log.info("创建群聊:{}", groupInfo);
                }
            } else {
                log.info("导入openIM 用户失败:{}", result);
            }
        }

        // 登录token
        OpenIMTokenDTO openIMTokenDTO = new OpenIMTokenDTO(openIMConfig.getSecret(), openIMLoginDTO.getPlatformID(), uuid.toString());
        OpenIMResultVo<OpenIMTokenVo> tokenResult = openIMApi.userToken(openIMTokenDTO);
        tokenResult.getData().setImUserId(one.getUuid().toString());
        return tokenResult;
    }

    @Override
    public OpenIMResultVo<OpenIMTokenVo> loginIMCustomer(ImCustomer imCustomer) {
        OpenIMConfig openIMConfig = OpenIMConfig.getOpenIMConfig();
        ImCustomer one = lambdaQuery().eq(ImCustomer::getUsername, imCustomer.getUsername())
                .eq(ImCustomer::getPassword, imCustomer.getPassword())
                .one();
        if (null != one) {
            if (one.getStatus() != 0) {
                throw new CustomException("客服被禁用");
            }
            // 登录IM系统
            OpenIMTokenDTO openIMTokenDTO = new OpenIMTokenDTO(openIMConfig.getSecret(), imCustomer.getPlatformID(), one.getImId());
            OpenIMResultVo<OpenIMTokenVo> tokenResult = openIMApi.userToken(openIMTokenDTO);
            // 登录用户系统
            LoginUserIM loginUserIM = new LoginUserIM();
            BeanUtils.copyBeanProp(loginUserIM, one);
            LoginUser loginUser = new LoginUser(loginUserIM);
            String loginToken = tokenService.createToken(loginUser);
            tokenResult.getData().setLoginToken(loginToken);
            tokenResult.getData().setImUserId(one.getImId());
            return tokenResult;
        } else {
            throw new CustomException(("账号或密码错误"));
        }
    }

}